﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using KVB.Common;
using Customer_Profile.eCard.DBDao;
using Customer_Profile.Admin;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace Customer_Profile.eCard
{
    public partial class EntityDealSearch : System.Web.UI.Page
    {
        string strUserName = "";
        string strUserID = "";
        string strEntityID = "";
        string strEntity = "";
        string sumInitAmount = "";
        string sumDueAmount = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            Comm.CheckSession(this.Page, "/login.aspx", "usermodel");
            if (Session["usermodel"] != null)
            {
                strUserID = ((UserInfoEntity)Session["usermodel"]).UserLoginId;
                strUserName = ((UserInfoEntity)Session["usermodel"]).UserName;
                strEntityID = ((UserInfoEntity)Session["usermodel"]).UserEntityID;
                strEntity = ((UserInfoEntity)Session["usermodel"]).UserOffice;
            }
            else
            {
                Log.WriteDefaultLog("main_01 Page_Load", "Session is null");
                return;
            }

            DataSet dsProd = ProductDao.getAllProduct("ALL");
            DevExpress.Web.ASPxEditors.ASPxListBox listbox = (DevExpress.Web.ASPxEditors.ASPxListBox)ASPxDropDownEdit1.FindControl("listBox");
            listbox.DataSource = dsProd;
            listbox.TextField = "procduct_name";
            listbox.ValueField = "procduct_code";
            listbox.DataBind();

            DevExpress.Web.ASPxEditors.ListEditItem li = new DevExpress.Web.ASPxEditors.ListEditItem("选择全部");
            listbox.Items.Insert(0, li);        

            if (!Page.IsPostBack)
            {
                Comm.BindDll(ref dropDealStatus, "dealStatus", true, "");
                txtcreatedatebegin.Text = DateTime.Now.AddDays(-7).ToString("yyyy-MM-dd");
                txtcreatedateend.Text = DateTime.Now.ToString("yyyy-MM-dd");
            }
            bindGrid();
        }

        private void bindGrid()
        {
            try
            {
                string strWhere = "where d.entity_id='" + strEntityID + "'"; //" where input_userid='" + strUserID + "' ";  
                if (txtCardNo.Text.Trim() != "")
                    strWhere += " and d.card_no ='" + txtCardNo.Text.Trim() + "'";
                if (txtCpartyName.Text.Trim() != "")
                    strWhere += " and c.cparty_name like '%" + txtCpartyName.Text.Trim() + "%'";                

                if (!ASPxDropDownEdit1.Text.Trim().Equals(""))
                {
                    strWhere += " And prod_code in (select STR1 from dbo.fn_SPLITSTR('" + ASPxDropDownEdit1.Text.Trim() + "',';')) ";
                }

                if (dropDealStatus.SelectedIndex > 0)
                {
                    strWhere += " and d.status = '" + dropDealStatus.SelectedItem.Value + "'";
                }
                if (txtcreatedatebegin.Text != "" && txtcreatedateend.Text != "")
                {
                    if (dropDateType.SelectedItem.Value.Equals("input_date"))
                        strWhere += " and convert(date,d.input_date) between '" + txtcreatedatebegin.Text.Trim() + "' and '" + txtcreatedateend.Text.Trim() + "'";
                    else if (dropDateType.SelectedItem.Value.Equals("submit_date"))
                        strWhere += " and convert(date,d.submit_date) between '" + txtcreatedatebegin.Text.Trim() + "' and '" + txtcreatedateend.Text.Trim() + "'";
                    else if (dropDateType.SelectedItem.Value.Equals("review_date"))
                        strWhere += " and convert(date,d.review_date) between '" + txtcreatedatebegin.Text.Trim() + "' and '" + txtcreatedateend.Text.Trim() + "'";
                    else if (dropDateType.SelectedItem.Value.Equals("value_date"))
                        strWhere += " and convert(date,d.value_date) between '" + txtcreatedatebegin.Text.Trim() + "' and '" + txtcreatedateend.Text.Trim() + "'";
                    else if (dropDateType.SelectedItem.Value.Equals("due_date"))
                        strWhere += " and convert(date,d.due_date) between '" + txtcreatedatebegin.Text.Trim() + "' and '" + txtcreatedateend.Text.Trim() + "'";
                }
                if (txtStartBalance.Text != "" && txtEndBalance.Text != "")
                {
                    strWhere += " and d.deal_balance between " + txtStartBalance.Text.Trim() + " and " + txtEndBalance.Text.Trim();
                }

                strWhere += " ORDER BY deal_no DESC";
                DataSet ds = DealDao.getCardDealsbysome(strWhere);
                if (ds != null && ds.Tables.Count > 0)
                {
                    sumInitAmount = ds.Tables[0].Compute("sum(initial_amount)", "1>0").ToString();
                    sumDueAmount = ds.Tables[0].Compute("sum(due_amount)", "1>0").ToString();
                    GvData.DataSource = ds.Tables[0];
                    GvData.DataBind();
                    
                }
                else
                {
                    GvData.DataBind();
                }
            }
            catch (Exception ex)
            {
                Log.WriteDefaultLog("bindGrid", ex.ToString());
                Response.Write(ex.ToString());
            }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {

        }

        protected void GvData_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            GvData.PageIndex = e.NewPageIndex;
            bindGrid();
        }

        protected void GvData_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {                
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@");

                    Label lbdealno = (Label)e.Row.Cells[0].Controls[1];

                    LinkButton lbcardno = (LinkButton)e.Row.Cells[1].Controls[1];
                    lbcardno.Attributes.Add("onclick", "javascript:window.open('CardDetail.aspx?cardno=" + lbcardno.Text + "');return false");

                    string strStatus = GvData.DataKeys[e.Row.RowIndex].Values["status"].ToString();                                         //e.Row.Cells[5].Text;
                    string input_userid = GvData.DataKeys[e.Row.RowIndex].Values["input_userid"].ToString();                                         //e.Row.Cells[5].Text;

                    string if_isExtension = e.Row.Cells[14].Text;

                    LinkButton lbAction = (LinkButton)e.Row.Cells[16].Controls[1];
                    if (if_isExtension.Equals("Y"))
                    {
                        //extension修改
                        if ((strStatus.Equals("E") || strStatus.Equals("EB")) && strUserID.Trim().Equals(input_userid.Trim()))
                        {
                            lbAction.Text = "修改";
                            lbAction.Attributes.Add("onclick", "javascript:window.location.href='ExtendAdd.aspx?dealno=" + lbdealno.Text + "';return false");
                        }
                        else
                        {
                            lbAction.Text = "";
                        }
                    }
                    else
                    {
                        //添加修改
                        if ((strStatus.Equals("I") || strStatus.Equals("IB"))&& strUserID.Trim().Equals(input_userid.Trim()))
                        {
                            lbAction.Text = "修改";
                            lbAction.Attributes.Add("onclick", "javascript:window.location.href='eCard_input.aspx?dealno=" + lbdealno.Text + "';return false");
                        }
                        else
                        {
                            lbAction.Text = "";
                        }
                    }
                }

                if (e.Row.RowType == DataControlRowType.Footer)
                {
                    e.Row.Cells[0].Text = "合计";
                    e.Row.Cells[0].ForeColor = System.Drawing.Color.White;
                    e.Row.Cells[7].Text = sumInitAmount;
                    e.Row.Cells[7].ForeColor = System.Drawing.Color.White;
                    e.Row.Cells[8].Text = sumDueAmount;
                    e.Row.Cells[8].ForeColor = System.Drawing.Color.White;
                }
            }
            catch (Exception ex)
            {
                Response.Write(ex.ToString());
            }
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            //标题
            byte[] bTitle = System.Text.Encoding.GetEncoding("UTF-8").GetBytes("交易信息" + "<br><br>");
            StringBuilder sb = new StringBuilder();
            sb.Append(System.Text.Encoding.GetEncoding("UTF-8").GetString(bTitle));

            //报表内容
            System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
            GvData.AllowPaging = false;
            GvData.ShowHeader = true;
            bindGrid();
            GvData.RenderControl(oHtmlTextWriter);
            byte[] bContent = System.Text.Encoding.GetEncoding("UTF-8").GetBytes(oStringWriter.ToString());
            sb.Append(System.Text.Encoding.GetEncoding("UTF-8").GetString(bContent));

            //输出
            System.Web.HttpContext.Current.Response.Clear();
            System.Web.HttpContext.Current.Response.Buffer = true;
            System.Web.HttpContext.Current.Response.Charset = "UTF-8";
            System.Web.HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=mmdeals.xls");
            System.Web.HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            System.Web.HttpContext.Current.Response.HeaderEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            System.Web.HttpContext.Current.Response.ContentType = "application/ms-excel";    //设置输出文件类型为excel文件。 
            System.Web.HttpContext.Current.Response.Write("<meta http-equiv=Content-Type content=\"text/html; charset=" + "UTF-8" + "\" >");

            string strExcel = sb.ToString();

            //去除超链接 
            strExcel = Regex.Replace(strExcel, "<a (.*?)>", "", RegexOptions.Compiled);
            strExcel = Regex.Replace(strExcel, "</a>", "");

            System.Web.HttpContext.Current.Response.Write(strExcel);
            System.Web.HttpContext.Current.Response.End();

        }

        public override void VerifyRenderingInServerForm(Control control)
        {
        }
    }
}